import store from '@/store/index.js'

const getEnvUrl = async (url) => {
  let userTmp1 = uni.getStorageSync('user')
  if (!userTmp1) {
    uni.reLaunch({ url: '/pages/profile/login' })
    return
  }
  
  let user = JSON.parse(userTmp1)
  if (!user.serverip || !user.serverport) {
    uni.reLaunch({ url: '/pages/profile/login' })
    return
  }
  
  // 拼接基础服务器地址
  let serverUrl = `${user.serverip}:${user.serverport}`
  if (!serverUrl.startsWith('http')) {
    serverUrl = `http://${serverUrl}`
  }
  
  // 处理相对路径URL（避免双斜杠）
  if (!url.startsWith('http')) {
    url = url.startsWith('/') ? `${serverUrl}${url}` : `${serverUrl}/${url}`
  }
  
  // 手动构建参数数组（不转义）
  const params = [
    `X-Emby-Client-Version=${user.deviceVersion || ''}`,
    `X-Emby-Client=Emby+app`,
    `X-Emby-Device-Name=${user.deviceName || ''}`,
    `X-Emby-Device-Id=${user.deviceId || ''}`,
    `X-Emby-Language=zh-cn`
  ]
  
  // 添加token参数
  const token = uni.getStorageSync('token')
  if (token) {
    params.push(`X-Emby-Token=${token}`)
  }
  
  // 拼接参数（不转义）
  const queryAppend = params.join('&')
  if (!queryAppend) return url
  
  // 拼接URL
  if (url.includes('?')) {
    url += `&${queryAppend}`
  } else {
    url += `?${queryAppend}`
  }
  
  return url
}

const post = async (url, postData, storeObj = null) => {
	url = await getEnvUrl(url)
	const data = Object.assign(postData ? postData : {}, {
		// timestamp: new Date().getTime()
	})

	let storeTemp = storeObj || store
	// console.log("当前请求地址"+url+";参数"+JSON.stringify(data))
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'POST',
			data: data,
			// timeout: 60000,
			header: {
				clientType: 'app',
				Authorization: 'Bearer ' + storeTemp.state.token
			},
			success(result) {
				if (result.statusCode == 401) {
					if (result.data) {
						uni.showToast({
							title: result.data,
							icon: 'error'
						})
					}
					storeTemp.commit('logout')
					if(!url.includes("Users/authenticatebyname")){
						uni.reLaunch({
							url: '/pages/profile/login'
						})
					}
					reject(result)
				} else if (result.data && result.statusCode != 200) {
					if (result.data) {
						uni.showToast({
							title: result.data,
							icon: 'error'
						})
					}
					reject(result)
				} else {
					resolve(result.data)
				}
			},
			fail(err) {
				// 捕获错误信息
				console.error('请求失败', err);
				
				// 判断是否为连接被拒绝错误
				if (err.errMsg && err.errMsg.includes('ERR_CONNECTION_REFUSED')) {
				  console.log('连接被拒绝，跳转到登录页');
				  // 跳转到登录页
				  uni.reLaunch({
					url: '/pages/profile/login'
				  });
				} else {
				  // 处理其他错误
				  console.log('其他错误:', err.errMsg);
				  reject(event)
				}
			}
		})
	})
}

const get = async (url, getData, storeObj = null) => {
	url = await getEnvUrl(url)
	const data = Object.assign(getData ? getData : {}, {
		// timestamp: new Date().getTime()
	})
	let storeTemp = storeObj || store
    // console.log("当前请求地址"+url+";参数"+JSON.stringify(data))
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'GET',
			data: data,
			// timeout: 60000,
			header: {
				clientType: 'app',
				Authorization: 'Bearer ' + storeTemp.state.token
			},
			success(result) {
				if (result.statusCode == 401) {
					if (result.data) {
						uni.showToast({
							title: result.data,
							icon: 'error'
						})
					}
					storeTemp.commit('logout')
					if(!url.includes("Users/authenticatebyname")){
						uni.reLaunch({
							url: '/pages/profile/login'
						})
					}
					reject(result)
				} else {
					resolve(result.data)
				}
			},
			fail(err) {
				// 捕获错误信息
				console.error('请求失败', err);
				
				// 判断是否为连接被拒绝错误
				if (err.errMsg && err.errMsg.includes('request:fail')) {
				  console.error('连接被拒绝，跳转到登录页');
				  uni.showToast({
				  	title: '网络连接错误',
				  	icon: 'error',
				  })
				  uni.hideLoading()
				  // 跳转到登录页
				  uni.reLaunch({
					url: '/pages/profile/login'
				  });
				} else {
				  // 处理其他错误
				  console.log('其他错误:', err.errMsg);
				  reject(event)
				}
			}
		})
	})
}
const upload = async (filePath) => {
	url = getEnvUrl()
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url + '/public/upload',
			filePath: filePath,
			name: 'file',
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == 200) {
					const res = JSON.parse(uploadFileRes.data)
					resolve(res.data)
				} else {
					reject(uploadFileRes)
				}
			},
			fail(e) {
				reject(e)
				console.log('fail', e)
			}
		})
	})
}

export default {
	post,
	get,
	upload
}